package org.example.hashtable;

public class EmpLinkedList {

    private Emp head;
    //当添加雇员时，id是自增长的，在链表最后添加
    public void add(Emp emp){
        if (head == null){
            head = emp;
            return;
        }
        Emp curEmp =  head;
        while(curEmp.next != null){
            curEmp = curEmp.next;
        }
        curEmp.next = emp;
    }

    public Emp findById(int id){
        if (head == null){
            return null;
        }
        Emp curEmp = head;
        while(true) {
            if(curEmp.id == id) {//找到
                return curEmp;
            }
            //退出
            if(curEmp.next == null) {//说明遍历当前链表没有找到该雇员
               return null;
            }
            curEmp = curEmp.next;//以后
        }

    }

    public void delById(int id){
        if (head == null){
            System.out.println("雇员所在的链表为空");
            return;
        }
        if (head.id == id){
            head = head.next;
            System.out.println("雇员"+id+"号已删除");
            return;
        }
        Emp curEmp = head;
        while(curEmp != null){
            if (curEmp.next.id == id){
                curEmp.next = curEmp.next.next;
                System.out.println("雇员"+id+"号已删除");
                return;
            }
            curEmp = curEmp.next;
        }
        System.out.println("没有该员工信息");
    }

    //遍历链表
    public void list(int no){
        if (head == null){
            System.out.println("第"+(no+1)+"条链表为空");
            return;
        }
        System.out.println("第"+(no+1)+"条链表信息为：");
        //展示时一定要用辅助指针，切不可用head这个类属性来遍历
        Emp curEmp = head;
        while(true){
            System.out.printf("当前员工id为:%d,姓名为:%s",curEmp.id,curEmp.name);
            if (curEmp.next == null){
                break;
            }
            curEmp  =curEmp.next;
        }
        System.out.println();
    }
}

